'use strict';

const Controller = require('egg').Controller;

class OauthController extends Controller {
    async oauth() {
        const { ctx } = this;
        const { code } = ctx.request.body
        console.log(ctx.request.body)
        const res = await ctx.curl('https://gitee.com/oauth/token', {
            method: 'POST',
            data: {
                grant_type: 'authorization_code',
                code,
                client_id: '7d2351470a92b220703e37d4f1e047227ea2b21990bad36c1c4bd946b4f338d5',
                redirect_uri: 'http://localhost:8080/login',
                client_secret: 'f96f1fee23538a2cc33b51dca9ad2c8c2c7dbe78aeed04611cb65f281123edc9'
            },
            dataType: 'json'
        }
        )

        // console.log(res)
        const access_token = res.data.access_token;
        ctx.session.token = access_token

        const user = await ctx.curl(`https://gitee.com/api/v5/user?access_token=${access_token}`, {
            method: 'GET',
            dataType: 'json'
        })
        console.log(user.data)
        const {login,name,avatar_url}=user.data
        if (user.data.login) {
            const result = await this.app.mysql.insert('myuser', {
                username:login,
                password:'123456',
                nickname:name,
                img:avatar_url,
            });
            if(result.affectedRows){
                ctx.body={
                    code:200,
                    mes:'登录成功'
                }
            }else{
                ctx.body={
                    code:400,
                    mes:'登录失败'
                }
            }
        }else{
            ctx.body={
                code:400,
                mes:'登录失败'
            }
        }
    }
}

module.exports = OauthController;
